package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ljj
 * @create 2022-11-15-18:14
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER =new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) servletRequest;
        HttpServletResponse response1 = (HttpServletResponse) servletResponse;

        String requestURI = request1.getRequestURI();
        log.info("拦截请求：{}"+requestURI);
        String[] urls=new String []{
                "/employee/login",//登录 放行
                "/employee/logout",
                "/backend/**",  //后端静态资源
                "/front/**",     //前端静态资源
                "/user/sendMsg","/user/login"
        };
        boolean check = check(urls, requestURI);
        if (check){
            log.info("拦截放行：{}"+requestURI);
            filterChain.doFilter(request1,response1);
            return;
        }
       if( request1.getSession().getAttribute("employee")!=null){
           log.info("拦截放行：id{}"+request1.getSession().getAttribute("employee"));
           long id =(Long) request1.getSession().getAttribute("employee");
           log.info("doFilter id:{}",id);
           BaseContext.setCurrentId(id);
           filterChain.doFilter(request1,response1);
           return;
        }
        if( request1.getSession().getAttribute("user")!=null){
            log.info("拦截放行：id{}"+request1.getSession().getAttribute("user"));
            long id =(Long) request1.getSession().getAttribute("user");
            log.info("doFilter id:{}",id);
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request1,response1);
            return;
        }


        log.info("未登入");
       response1.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
    /**
     * 路径匹配
     */
    public boolean check(String [] strs,String requestUrl){
        for (String url : strs) {
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match){
                return true;

            }
        }
        return false;
    }
}
